package com.example.lxy.iot4;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.transform.Source;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int SHOW_HUM = 0;
    public static final int SHOW_TEM = 1;

    private Button sendRequest;
    private TextView responseTextHum;
    private TextView responseTextTem;
    private TextView timeText;
    private TextView HttpGetText;
    private TextView ResponseTxt;
    View    vAChar;
    private static  byte SendNum = 0;

    String LastResponseStrTemp = "";
    String LastResponseStrHum="";
    String ResponseStrTemp = "";
    String ResponseStrHum="";

    private double[] SourceDat=new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    private SupportLineUtils mLineUtils;
    private LinearLayout mLinearLayoutLine;

    private int iSourceDat = 0;
    private double GetValue = 0;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            String ResponseStr = "";
            try {
                String response = (String) msg.obj;
                JSONTokener json = new JSONTokener(response);
                JSONObject obj = (JSONObject) json.nextValue();
                GetValue = Double.valueOf( obj.getJSONObject("data").getString("current_value"));
                ResponseStr = obj.getJSONObject("data").getString("current_value").toString();


            }catch(Exception e){
                e.printStackTrace();
            }
            switch (msg.what) {
                case SHOW_HUM:
                    ResponseStrHum = ResponseStr;
                    responseTextHum.setText(ResponseStr + "%");
                    break;
                case SHOW_TEM:
                    ResponseStrTemp = ResponseStr;
                    responseTextTem.setText(ResponseStr + "℃");
                    SourceDat[iSourceDat] = GetValue;
                    iSourceDat++;
                    if(iSourceDat > 19){
                        iSourceDat = 0;
                    }
            }

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());
            String str = formatter.format(curDate);
            HttpGetText.setText("网络访问时间: " + str);
            if(!ResponseStrTemp.equals(LastResponseStrTemp) || !ResponseStrHum.equals(LastResponseStrHum)) {
                timeText.setText("数值更新时间: " + str);
            }
            LastResponseStrTemp = ResponseStrTemp;
            LastResponseStrHum = ResponseStrHum;


            RefreshNumberPoint(SourceDat);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendRequest = (Button) findViewById(R.id.send_request);
        responseTextHum = (TextView) findViewById(R.id.response_Hum);
        responseTextTem = (TextView)findViewById(R.id.response_Tem);
        timeText = (TextView)findViewById(R.id.txtUpdateTime);
        HttpGetText = (TextView)findViewById(R.id.HttpGetime);
    //    ResponseTxt = (TextView)findViewById(R.id.response_Txt);

        mLinearLayoutLine = (LinearLayout) findViewById(R.id.linearLayout_line_main);
        mLineUtils = new SupportLineUtils(this.getApplicationContext());
        vAChar = mLineUtils.initLineGraphView(SourceDat);
        mLinearLayoutLine.addView(vAChar);


        sendRequest.setOnClickListener(this);
        sendRequestWithHttpURLConnection();
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            Intent intent = new Intent(MainActivity.this,ChartActivity.class);
            startActivity(intent);
        }
    }
    private void sendRequestWithHttpURLConnection() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    if(SendNum == 0){
                        OneNet_GetTem();
                    }else if(SendNum == 1){
                        OneNet_GetHum();
                    }
                    SendNum ++;
                    if(SendNum >= 2){
                        SendNum = 0;
                    }
                    try {
                        Thread.sleep(5000);
                    }catch (Exception e){

                    }
                }
            }
        }).start();
    }
    private void OneNet_GetHum(){
        HttpRequest httpget = new HttpRequest();
        String strResult;
        httpget.setApiKey("4aZ0hDwVPEbnluhwLTtkIoTQC3E=");
        strResult = HttpRequest.sendGet("http://api.heclouds.com/devices/3221986/datastreams/Humidity", "");

        Message message = new Message();
        message.what = SHOW_HUM;
        // 将服务器返回的结果存放到Message中
        message.obj = strResult;
        handler.sendMessage(message);
    }
    private void OneNet_GetTem(){
        HttpRequest httpget = new HttpRequest();
        String strResult;
        httpget.setApiKey("4aZ0hDwVPEbnluhwLTtkIoTQC3E=");
        strResult = HttpRequest.sendGet("http://api.heclouds.com/devices/3221986/datastreams/Temperature", "");

        Message message = new Message();
        message.what = SHOW_TEM;
        // 将服务器返回的结果存放到Message中
        message.obj = strResult;
        handler.sendMessage(message);
    }
    protected void RefreshNumberPoint(double LinePointData[]){

        try {

             mLinearLayoutLine.removeView(vAChar);
             mLineUtils = new SupportLineUtils(this.getApplicationContext());
             vAChar = mLineUtils.initLineGraphView(SourceDat);
             mLinearLayoutLine.addView(vAChar);

        }catch(Exception e){
            e.printStackTrace();
        }


    }
}